<?php
use app\models\Nav;

/*面包屑*/
function smarty_block_crumbs($params, $content, Smarty_Internal_Template $template, &$repeat)
{
    $app_id = Yii::$app->params['app_id'];
    $crumbs = '';
    $title = '';
    if(isset($params['url'])){
    	$tmp = Nav::find()
	            ->select(['navid', 'allparentid', 'allchildid'])
	            ->where('app_id = :app_id and url = :url and display = 2', [':app_id' => $app_id, ':url' => $params['url']])
                ->orderBy(['level' => SORT_DESC])
	           	->one();
	    // P($tmp);
    }else if(isset($params['id'])){
    	$tmp = Nav::find()
	            ->select(['allparentid', 'allchildid'])
	            ->where('app_id = :app_id and navid = :id and display = 2', [':app_id' => $app_id, ':id' => $params['id']])
	           	->one();
    }
    if(!is_null($tmp)){
        $nav = Nav::find()
        		->select(['name', 'preview', 'url', 'url_target', 'outside', 'args'])
        		->where(['or', ['navid' => $tmp->navid],['in', 'navid', explode(',', $tmp->allparentid)]])
        		->orderBy(['level' => SORT_ASC])
	            ->asArray()->all();
        // P($nav);
        if(!is_null($nav)){
            foreach($nav as $k => $v){
                if(isset($v['url']) and ($v['outside'] == 1) and (substr($v['url'], 0, 7) != 'http://')){
                    $nav[$k]['url'] = '/' . $nav[$k]['url'];
                }
                unset($nav[$k]['outside']);

                if(count($nav) == ($k +1)){
                    $crumbs .= '<a href="' . $nav[$k]['url'] . '">' . $v['name'] . '</a>';
                    $title = $v['name'];
                }else{
                    if(isset($params['separator'])){
                        $crumbs = '<a href="' . $nav[$k]['url'] . '">' . $v['name'] . '</a>' . $params['separator'];
                    }else{
                        $crumbs = '<a href="' . $nav[$k]['url'] . '">' . $v['name'] . '</a>' . '>';
                    }
                }
            }
            // P($nav);
        }
    }
    // P($crumbs);
    $template->assign("title", $title);
    $template->assign("crumbs", $crumbs);
    return $content;

}